package com.example.controller;

import com.example.entity.Book;
import com.example.repository.BookRepository;
import com.example.service.CoverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

@Controller
@RequestMapping("/books")
public class BookController {
    private static final Logger logger = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private CoverService coverService;

    @GetMapping
    public String listBooks(Model model, @RequestParam(required = false) String search) {
        try {
            if (search != null && !search.isEmpty()) {
                model.addAttribute("books", bookRepository.findByTitleContainingOrAuthorContaining(search, search));
            } else {
                model.addAttribute("books", bookRepository.findAll());
            }
            return "book/list";
        } catch (Exception e) {
            logger.error("列出图书时发生错误", e);
            throw new RuntimeException("列出图书时发生错误", e);
        }
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        try {
            Book book = new Book();
            book.setPrice(0.0);
            book.setStock(0);
            book.setCoverUrl(coverService.generateRandomCover());
            model.addAttribute("book", book);
            return "book/form";
        } catch (Exception e) {
            logger.error("显示添加表单时发生错误", e);
            throw new RuntimeException("显示添加表单时发生错误", e);
        }
    }

    @PostMapping("/add")
    public String addBook(@ModelAttribute Book book, @RequestParam(value = "coverFile", required = false) MultipartFile coverFile) {
        try {
            logger.info("添加新图书: {}", book);
            if (coverFile != null && !coverFile.isEmpty()) {
                String coverUrl = coverService.uploadCover(coverFile);
                book.setCoverUrl(coverUrl);
            } else if (book.getCoverUrl() == null || book.getCoverUrl().isEmpty()) {
                book.setCoverUrl(coverService.generateRandomCover());
            }
            bookRepository.save(book);
            return "redirect:/books";
        } catch (IOException e) {
            logger.error("处理封面图片时发生错误", e);
            throw new RuntimeException("处理封面图片时发生错误", e);
        } catch (Exception e) {
            logger.error("添加图书时发生错误", e);
            throw new RuntimeException("添加图书时发生错误", e);
        }
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        try {
            Book book = bookRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("图书未找到: " + id));
            if (book.getCoverUrl() == null || book.getCoverUrl().isEmpty()) {
                book.setCoverUrl(coverService.generateRandomCover());
            }
            model.addAttribute("book", book);
            return "book/form";
        } catch (Exception e) {
            logger.error("显示编辑表单时发生错误, id: " + id, e);
            throw new RuntimeException("显示编辑表单时发生错误", e);
        }
    }

    @PostMapping("/edit/{id}")
    public String updateBook(@PathVariable Long id, @ModelAttribute Book book, 
                           @RequestParam(value = "coverFile", required = false) MultipartFile coverFile) {
        try {
            logger.info("更新图书: {}", book);
            if (coverFile != null && !coverFile.isEmpty()) {
                String coverUrl = coverService.uploadCover(coverFile);
                book.setCoverUrl(coverUrl);
            } else if (book.getCoverUrl() == null || book.getCoverUrl().isEmpty()) {
                book.setCoverUrl(coverService.generateRandomCover());
            }
            book.setId(id);
            bookRepository.save(book);
            return "redirect:/books";
        } catch (IOException e) {
            logger.error("处理封面图片时发生错误", e);
            throw new RuntimeException("处理封面图片时发生错误", e);
        } catch (Exception e) {
            logger.error("更新图书时发生错误", e);
            throw new RuntimeException("更新图书时发生错误", e);
        }
    }

    @PostMapping("/delete/{id}")
    public String deleteBook(@PathVariable Long id) {
        try {
            logger.info("删除图书, id: {}", id);
            bookRepository.deleteById(id);
            return "redirect:/books";
        } catch (Exception e) {
            logger.error("删除图书时发生错误, id: " + id, e);
            throw new RuntimeException("删除图书时发生错误", e);
        }
    }
} 